'use strict'

const superagent = require('superagent');
let Promise = require('bluebird');
let request = Promise.promisify(require('request'));
exports.initAccessToken = async function (config) {
    try {
        let data = await getTokenAndTicket(config);
        global.cache.set('wechatToken', data)
    } catch (error) {
        throw error
    }
}
// 获取AccessToken 和 ticket
function getTokenAndTicket(config) {
    let appID = config.appID;
    let appSecret = config.appsecret;
    return new Promise((resolve, reject) => {
        let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appID}&secret=${appSecret}`;
        request({ url, json: true }).then(res => {
            let data = res.body;
            let now = Date.now();
            let ticketUrl = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${data.access_token}&type=jsapi`;
            request({ url: ticketUrl, json: true }).then(result => {
                let expires_in = now + (result.body.expires_in - 20) * 1000;
                data.expires_in = expires_in;
                data.ticket = result.body.ticket;
                resolve(data)
            })
        })
    })
    /* return new Promise((resolve, reject) => {
        superagent.get(url).then(function (res) {
            let data = res.body;
            let now = Date.now();
            let ticketUrl = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${data.access_token}&type=jsapi`;
            superagent.get(ticketUrl).then(result => {
                let expires_in = now + (result.body.expires_in - 20) * 1000;
                data.expires_in = expires_in;
                data.ticket = result.body.ticket;
                resolve(data)
            })
        })
    }) */
}







/* // let Promise = require('bluebird');
exports.readFileAsync = function (fpath, encoding) {
    return new Promise((resolve, reject) => {
        fs.readFile(fpath, encoding, (err, res) => {
            if (err) reject(err);
            else resolve(res)
        })
    })
}
exports.writeFileAsync = function (fpath, content) {
    return new Promise((resolve, reject) => {
        fs.writeFile(fpath, content, (err) => {
            if (err) reject(err)
            else resolve()
        })
    })
} */